<?php
/**
 * Author panxu
 * Date   2019/8/13 14:27
 */
namespace App\WebSocket;

use App\Utility\Pool\MysqlPool;
use App\Utility\Pool\RedisPool;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\EasySwoole\Swoole\Task\TaskManager;
use EasySwoole\Socket\AbstractInterface\Controller;

class Index extends Controller
{


    function hello()
    {
        $this->response()->setMessage('call hello arg:'.json_encode($this->caller()->getArgs()));
    }


    function who()
    {
        $this->response()->setMessage('fd is '.$this->caller()->getClient()->getFd());
    }

    function ping()
    {
        $this->response()->setMessage($this->getMsg(['arg'=>$this->caller()->getArgs(),'fd'=>$this->caller()->getClient()->getFd()],'ping'));
    }


    function delay()
    {
        $this->response()->setMessage('this is delay action');
        $client = $this->caller()->getClient();

        // 异步推送, 这里直接 use fd也是可以的
        TaskManager::async(function () use ($client){
            $server = ServerManager::getInstance()->getSwooleServer();
            $i = 0;
            while ($i < 5) {
                sleep(1);
                $server->push($client->getFd(),'push in http at '. date('H:i:s'));
                $i++;
            }
        });
    }

    protected function getMsg($msg,$type='error'){
        return json_encode(['type'=>$type,'msg'=>$msg]);
    }
    
    
    function addfriend()
    {
        $args = $this->caller()->getArgs();
        $token = $args['token'];
        $fuid = $args['fuid'];
        $msg = $args['msg'];
        $group = $args['group'];
        $redis = RedisPool::defer();
        $info = $redis->get($token);
        $mine = json_decode($info,true);
        $uid = $mine['id'];
        if($redis->exists('uid_'.$fuid))
        {
            //在线
            $fd = $redis->get('uid_'.$fuid);
            $server = ServerManager::getInstance()->getSwooleServer();
            $server->push($fd,$this->getMsg(['user'=>$mine,'msg'=>$msg],'addfriend'));
        }
        else
        {
            $db = MysqlPool::defer();
            $username = $mine['username'];
            $avatar = $mine['avatar'];
            //离线
            $data = [
                'uid'=>$uid,
                'fuid'=>$fuid,
                'content'=>json_encode(compact('uid','fuid','msg','group','username','avatar')),
                'type'=>1,
                'status'=>2
            ];
            $id = $db->insert('ch_off_message',$data);
        }

    }
    
    
    function agree()
    {
        $args = $this->caller()->getArgs();
        $token = $args['token'];
        $fuid = $args['fuid'];
        $group = $args['group'];
        //token同意来自fuid的好友请求
        //推送消息告诉fuid
        $redis = RedisPool::defer();
        $info = $redis->get($token);
        $mine = json_decode($info,true);

        $db = MysqlPool::defer();
        $ms = [
            'uid'=>0,
            'fuid'=>$fuid,
            'content'=>$mine['username'].'同意了你得好友请求。',
            'type'=>3,
            'status'=>2,
        ];
        $db->insert('ch_off_message',$ms);
        if($redis->exists('uid_'.$fuid))
        {
            $fd = $redis->get('uid_'.$fuid);
            $infos = $db->where('fuid',$fuid)->where('type',[1,3],'in')->where('status',2)->get('ch_off_message');
            $count = count($infos);
            $server = ServerManager::getInstance()->getSwooleServer();
            $server->push($fd,$this->getMsg($count,'msgbox_count'));
        }
    }
    
    
    function refuse()
    {
        $args = $this->caller()->getArgs();
        $token = $args['token'];
        $fuid = $args['fuid'];
        $group = $args['group'];
        //token拒绝来自fuid的好友请求
    }


    //发送消息
    function sendmsg()
    {
        $args = $this->caller()->getArgs();
        $mine = $args['mine'];
        $to = $args['to'];
//        $msg = $mine['content'];
        $mine['timestamp'] = time() * 1000;
        $mine['mine'] = false;
        $mine['type'] = "friend";
        $mine['fromid'] = $mine['id'];
        $redis = RedisPool::defer();
        //聊天消息记录
        $db = MysqlPool::defer();
        $db->insert('ch_friend_message',[
            'uid'=>$mine['id'],
            'fuid'=>$to['id'],
            'content'=>json_encode($mine),
            'type'=>2,
        ]);
        if($redis->exists('uid_'.$to['id']))
        {
            $fd = $redis->get('uid_'.$to['id']);
            $server = ServerManager::getInstance()->getSwooleServer();
            $server->push($fd, $this->getMsg($mine,'newMsg'));
        }else
        {

            $db->insert('ch_off_message',[
                'uid'=>$mine['id'],
                'fuid'=>$to['id'],
                'content'=>json_encode($mine),
                'type'=>2,
                'status'=>2,
            ]);
        }


    }
}